import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import PublicActivities from '../views/PublicActivities.vue'
import ActivityDetail from '../views/ActivityDetail.vue'
import ActivityManagement from '../views/ActivityManagement.vue'
import activities from '../data/activities'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Login',
    component: Login
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: { requiresAuth: true }
  },
  {
    path: '/public-activities',
    name: 'PublicActivities',
    component: PublicActivities,
    meta: { requiresAuth: true },
    props: { activities }
  },
  {
    path: '/public-activities/:id',
    name: 'ActivityDetail',
    component: ActivityDetail,
    meta: { requiresAuth: true },
    props: (route) => ({
      activity: activities.find(a => a.id === parseInt(route.params.id))
    })
  },
  {
    path: '/activity-management',
    name: 'ActivityManagement',
    component: ActivityManagement,
    meta: { 
      requiresAuth: true,
      requiresAdmin: true 
    }
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('user')
  const user = isAuthenticated ? JSON.parse(isAuthenticated) : null
  
  // 检查是否需要登录
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!isAuthenticated) {
      next('/login')
    } else {
      // 检查是否需要管理员权限
      if (to.matched.some(record => record.meta.requiresAdmin)) {
        if (user && user.role === 'admin') {
          next()
        } else {
          alert('无权限访问此页面')
          next('/home')
        }
      } else {
        next()
      }
    }
  } else {
    next()
  }
})

export default router